<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ include file="/WEB-INF/inc/taglib.inc" %>
<%@ include file="/WEB-INF/inc/script.inc" %>
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
	<base href="${base}">
    <title>中金通 | 修改企业</title>

    <link href="css/bootstrap.min.css" rel="stylesheet">
    <link href="font-awesome/css/font-awesome.css" rel="stylesheet">

	<!-- Data Tables -->
    <link href="css/plugins/dataTables/dataTables.bootstrap.css" rel="stylesheet">
    <link href="css/plugins/dataTables/dataTables.responsive.css" rel="stylesheet">
    <link href="css/plugins/dataTables/dataTables.tableTools.min.css" rel="stylesheet">
    
    <!-- 向导css -->
    <link href="css/plugins/steps/jquery.steps.css" rel="stylesheet">
    
    <link href="css/animate.css" rel="stylesheet">
    <link href="css/style.css" rel="stylesheet">

    <link href="css/plugins/datapicker/datepicker3.css" rel="stylesheet">
    
    <!-- 下拉框 -->
    <link href="css/plugins/chosen/chosen.css" rel="stylesheet">
    
    <style type="text/css">
   	 textarea{
     	resize:none;
    	}
    .detailText
	{
	 padding:6px 12px; 
	}
	
	.form-control[readonly]{
		background-color: #fff;
			opacity: 1;
	}
    </style>
</head>

<body>

    <div id="wrapper">

    	<!-- 左侧菜单 -->
        <jsp:include page="/WEB-INF/jsp/common/main-menu.jsp"></jsp:include>

        <div id="page-wrapper" class="gray-bg">
        <div class="row border-bottom">
        <!-- 头部工具栏区 -->
        <jsp:include page="/WEB-INF/jsp/common/main-header.jsp"></jsp:include>
        </div>
            <div class="row wrapper border-bottom white-bg page-heading">
                <div class="col-lg-10">
                    <h2>产品管理</h2>
                    <ol class="breadcrumb">
                        <li>
                            <a href="common/platform">Home</a>
                        </li>
                        <li>
                            <a href="#">产品管理</a>
                        </li>
                        <li>
                         	<a href="#">产品列表</a>
                        </li>
                        <li class="active">
                            <strong>产品编辑</strong>
                        </li>
                    </ol>
                </div>
                <div class="col-lg-2">

                </div>
            </div>
		
		<div class="row" style="margin-top:10px;">
			<div class="col-md-12">
                    <div class="tabs-container">
                        <ul class="nav nav-tabs">
                            <li>
								<a href="product/list">
									 产品列表
								</a>
							</li>
							<li>
								<a href="product/add">
								 	新增产品
								</a>
							</li>
							<li class="active">
								<a>
									 产品编辑
								</a>
							</li>
                        </ul>
                        <div class="tab-content">
                            <div class="tab-pane active">
                                <div class="panel-body">
                                    <div class="wrapper wrapper-content animated fadeInRight ecommerce">
						                        <div><!-- class="ibox-content" -->
						                           <!-- class="ibox-content" -->
											<form method="post" id="addForm" enctype="multipart/form-data" action="enterprise/doAdd" class="form-horizontal wizard-big">
												<input type="text" name="id" style="display:none" value="${enterprise.id}">
												
												<!--Detail form start-->
												<h1>基本信息</h1>
                                				<fieldset>
                                    				<!-- <h2>Account Information</h2> -->
						                              <div class="row">
									                    <div class="col-sm-6">
									                        <div class="form-group">
									                            <label class="col-sm-4 control-label"><font color="red">*&nbsp;&nbsp;</font>企业名称</label>
						                                        <div class="col-sm-8">
						                                    	   <input type="text" name="name" class="form-control" placeholder="企业名称" value="${enterprise.name}">
						                                        </div>
									                        </div>
									                    </div>
									                    <div class="col-sm-6">
									                        <div class="form-group">
									                        	<label class="col-sm-2 control-label" style="position:relative;margin-left:-18px;width:19%;">成立日期</label>
						                                        <div class="col-sm-8">
						                                    	   <input type="text" name="createTime" class="form-control" placeholder="成立日期" value="${enterprise.createTime}">
						                                        </div>
									                        </div>
									                    </div>
									                 </div>
						                            <!-- <div class="hr-line-dashed"></div> -->
						                             <div class="row">
									                    <div class="col-sm-6">
									                        <div class="form-group">
									                            <label class="col-sm-4 control-label"><font color="red">*&nbsp;&nbsp;</font>法定代表人</label>
						                                        <div class="col-sm-8">
						                                    	   <input type="text" name="legalPerson" class="form-control" placeholder="法定代表人" value="${enterprise.legalPerson}">
						                                        </div>
									                        </div>
									                    </div>
									                    <div class="col-sm-6">
									                        <div class="form-group">
									                            <label class="col-sm-2 control-label">工商注册号</label>
						                                        <div class="col-sm-8">
						                                    	   <input type="text" name="businessRegistrationNo" class="form-control" placeholder="工商注册号" value="${enterprise.businessRegistrationNo}">
						                                        </div>
									                        </div>
									                    </div>
									                 </div>
						                            <!--  <div class="hr-line-dashed"></div> -->
						                              <div class="row">
									                    <div class="col-sm-12">
									                        <div class="form-group">
									                            <label class="col-sm-4 control-label">地址</label>
						                                        <div class="col-sm-8">
						                                    	   <input type="text" name="address" class="form-control" placeholder="地址" value="${enterprise.address}">
						                                        </div>
									                        </div>
									                    </div>
									                 </div>
						                             <!-- <div class="hr-line-dashed"></div> -->
						                              <div class="row">
									                    <div class="col-sm-6">
									                        <div class="form-group">
									                            <label class="col-sm-4 control-label">联系人</label>
						                                        <div class="col-sm-8">
						                                    	   <input id="openDate" type="text" name="contacts" class="form-control" placeholder="联系人" value="${enterprise.contacts}">
						                                        </div>
									                        </div>
									                    </div>
									                    <div class="col-sm-6">
									                        <div class="form-group">
									                        	<label class="col-sm-2 control-label">手机号码</label>
						                                        <div class="col-sm-8">
						                                    	   <input type="text" name="mobile" class="form-control" placeholder="手机号码" value="${enterprise.mobile}">
						                                        </div>
									                        </div>
									                    </div>
									                 </div>
												</fieldset>
												<h1>认购合同</h1>
                                				<fieldset>
												</fieldset>
												<h1>产品档次</h1>
                                				<fieldset>
									            </fieldset>
									            <h1>佣金设置</h1>
                                				<fieldset>
												</fieldset>
												<h1>相关文件</h1>
                                				<fieldset>
                                				</fieldset>
                                				<h1>同类产品</h1>
                                				<fieldset>
                                					<div class="tab-content">
								                   		<div class="tab-pane active">
								                            <div class="panel-body">
								                                 <div class="wrapper wrapper-content animated fadeInRight ecommerce">
																	
											                    </div>
														    </div>
								        			   </div>
								                  </div> 
                                				</fieldset>
											</form>





											<!-- update model start -->
											<div class="modal inmodal fade" id="updateModel" tabindex="-1" role="dialog" aria-hidden="true">
												<div class="modal-dialog modal-lg">
													<div class="modal-content">
														<div class="modal-header">
															<button type="button" class="close" data-dismiss="modal">
																<span aria-hidden="true">&times;</span>
																<span class="sr-only">Close</span>
															</button>
															<h4 class="modal-title" id="grade_edit_id">产品档次</h4>
														</div>
														<div class="modal-body">
															<div id="updateBody"></div>
															<form id="gradeForm" class="form-horizontal">
																<input type="text" style="display: none" id="productId" name="productId" class="form-control" value="${enterprise.id}"> 
																<input type="text" style="display: none" id="gradeId" name="id" class="form-control">
																<div class="form-group">
																	<label class="col-sm-3 control-label">
																		档次
																	</label>
																	<div class="col-sm-8">
																		<input type="text" id="grade" name="grade" class="form-control">
																	</div>
																</div>
																<div class="form-group">
																	<label class="col-sm-3 control-label">
																		<font color="red">*&nbsp;&nbsp;</font>认购最小金额(万元)
																	</label>
																	<div class="col-sm-8">
																		<input type="text" id="subScopeStart" name="subScopeStart" class="form-control">
																	</div>
																</div>
																<div class="form-group">
																	<label class="col-sm-3 control-label">
																		<font color="red">*&nbsp;&nbsp;</font>认购最大金额(万元)
																	</label>
																	<div class="col-sm-8">
																		<input type="text" id="subScopeEnd" name="subScopeEnd" class="form-control">
																	</div>
																</div>
																<div class="form-group">
																	<label class="col-sm-3 control-label">
																		<font color="red">*&nbsp;&nbsp;</font>预期收益
																	</label>
																	<div class="col-sm-8">
																		<input type="text" id="prospectiveEarnings" name="prospectiveEarnings" class="form-control">
																	</div>
																</div>
																<div class="form-group">
																	<label class="col-sm-3 control-label">
																		备注
																	</label>
																	<div class="col-sm-8">
																		<input type="text" id="grade_remark" name="remark" class="form-control">
																	</div>
																</div>
															</form>
														</div>
														<div class="modal-footer">
															<button type="button" class="btn btn-white" data-dismiss="modal">取 消</button>
															<button type="button" id="saveModel" class="btn btn-primary">保 存</button>
														</div>
													</div>

												</div>
											</div>
											<!-- update model end -->
											
											
											<!-- update model start -->
											<div class="modal inmodal fade" id="updateModel_comm" tabindex="-1" role="dialog"  aria-hidden="true">
						                         <div class="modal-dialog modal-lg">
						                              <div class="modal-content">
						                                   <div class="modal-header">
						                                        <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>
						                                        <h4 class="modal-title" id="d_title">待填写</h4>
						                                   </div>
						                                   <div class="modal-body">
							                                   <div id="updateBody_comm"></div>
							                                   <div class="form-horizontal">
							                                		<div class="form-group"><label class="col-sm-2 control-label" id="d_old_val">待填写</label>
							                                    		<div class="col-sm-8"><input readonly style="border:0px;background:#0f0;background-color:transparent;" type="text" id="old_val" class="form-control" >
							                                			</div>
							                                		</div>
							                                		<div class="form-group"><label class="col-sm-2 control-label" id="d_new_val">待填写</label>
							                                    		<div class="col-sm-8"><input type="text" id="new_val" class="form-control" >
							                                            </div>
							                                		</div>
							                                		<span id="renameInfo" class="col-sm-2 control-label"></span>
							                                   </div>
														   </div>
						                                   <div class="modal-footer">
						                                        <button type="button" class="btn btn-white" data-dismiss="modal">取 消</button>
						                                        <button type="button" id="saveModel" class="btn btn-primary" onclick="setRate()">保 存</button>
						                                   </div>
						                                </div>
						                            </div>
						                       </div>
						                       <!-- update model end --> 
						                          
						                           <!-- update model start -->
									<div class="modal inmodal fade" id="updateModel_relatedFile" tabindex="-1" role="dialog"  aria-hidden="true">
		                                <div class="modal-dialog modal-lg">
		                                    <div class="modal-content">
		                                        <div class="modal-header">
		                                            <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>
		                                            <h4 class="modal-title">重命名</h4>
		                                        </div>
		                                        <div class="modal-body">
		                                        <div id="updateBody_relatedFile"></div>
		                                        <div class="form-horizontal">
		                                			<div class="form-group"><label class="col-sm-2 control-label">文件原名</label>
		                                    			<div class="col-sm-8"><input readonly style="border:0px;background:#0f0;background-color:transparent;" type="text" id="o_renameFileName" class="form-control" >
		                                				</div>
		                                			</div>
		                                			<div class="form-group"><label class="col-sm-2 control-label"><font color="red">*&nbsp;&nbsp;</font>文件新名</label>
		                                    			<div class="col-sm-8"><input type="text" id="renameFileName" class="form-control" >
		                                            	</div>
		                                			</div>
		                                			<span id="renameInfo" class="col-sm-2 control-label"></span>
		                                       </div>
													
		                                        </div>
		                                        <div class="modal-footer">
		                                            <button type="button" class="btn btn-white" data-dismiss="modal">取 消</button>
		                                            <button type="button" id="saveModel" class="btn btn-primary" onclick="renameFile()">保 存</button>
		                                        </div>
		                                    </div>
		                                </div>
		                            </div>
		                            <!-- update model end -->   
		                            
		                            <!-- update model start -->
										<div class="modal inmodal fade" id="newProductGroup" tabindex="-1" role="dialog"  aria-hidden="true">
					                         <div class="modal-dialog modal-lg">
					                              <div class="modal-content">
					                                   <div class="modal-header">
					                                        <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>
					                                        <h4 class="modal-title">新增产品组别</h4>
					                                    </div>
					                                    <div class="modal-body">
						                                    <div id="updateBody_newProductGroup"></div>
						                                    <div class="form-horizontal">
							                                	<div class="form-group">
							                                		<label class="col-sm-2 control-label"><font color="red">*&nbsp;&nbsp;</font>组别名称</label>
							                                    	<div class="col-sm-8">
							                                    		<input type="text" id="newProductGroupName" class="form-control" >
							                                         </div>
							                                	 </div>
							                                	 <span id="renameInfo" class="col-sm-2 control-label"></span>
						                                   </div>
					                                    </div>
					                                    <div class="modal-footer">
					                                         <button type="button" class="btn btn-white" data-dismiss="modal">取 消</button>
					                                         <button type="button" class="btn btn-primary" onclick="newProductGroup()">保 存</button>
					                                    </div>
					                                </div>
					                           </div>
					                    </div>
					               <!-- update model end -->
						                            
										</div>
									</div>
								</div>
							</div>
						</div>
					</div>
				</div>
			</div>
		
        <!-- 底部版权 -->
        <jsp:include page="/WEB-INF/jsp/common/main-footer.jsp"></jsp:include>

        </div>
        </div>

   <!-- Mainly scripts -->
	<script src="js/jquery-2.1.1.js"></script>
	<script src="js/bootstrap.min.js"></script>
	<script src="js/plugins/metisMenu/jquery.metisMenu.js"></script>
	<script src="js/plugins/slimscroll/jquery.slimscroll.min.js"></script>
	<script src="js/jquery.serialize-object.min.js" type="text/javascript"></script>
	<script src="js/plugins/validate/jquery.validate.min.js" type="text/javascript"></script>
	<script src="js/plugins/validate/jquery.validate.messages-zh_CN.js" type="text/javascript"></script>
	<!-- Custom and plugin javascript -->
	<script src="js/inspinia.js"></script>
	<script src="js/plugins/pace/pace.min.js"></script>
	<script src="js/plugins/bootbox/bootbox.min.js" type="text/javascript"></script>
	<!-- Data picker -->
	<script src="js/plugins/datapicker/bootstrap-datepicker.js"></script>

	<!-- Data Tables -->
	<script src="js/plugins/dataTables/jquery.dataTables.min.js"></script>
	<script src="js/plugins/dataTables/dataTables.bootstrap.js"></script>
	<script src="js/plugins/dataTables/dataTables.responsive.js"></script>
	<script src="js/plugins/dataTables/dataTables.tableTools.min.js"></script>
    
    <!-- Steps -->
    <script src="js/plugins/staps/jquery.steps.min.js"></script>
    
	<!-- 业务 -->
	<script src="js/ajaxfileupload.js"></script>
	<script src="js/jquery.form.js"></script>
	<script src="js/product/product-add.js"></script>
	<script src="js/product/product-grade-module.js"></script>
	<script src="js/product/product-commission.js"></script> 
	<script src="js/product/FormatUtils.js"></script>
	
	<!-- Chosen -->
    <script src="js/plugins/chosen/chosen.jquery.js"></script>

	<!-- 产品基本信息 -->
	<script>
		$(document).ready(function() {
			ProductAdd.init();
			
			$("#addForm").steps({
                bodyTag: "fieldset",
                onStepChanging: function (event, currentIndex, newIndex)
                {
                	//$("a[href=#next]").css("display","");
                	//$("a[href=#finish]").css("display","none");
                	
                    // Always allow going backward even if the current step contains invalid fields!
                    if (currentIndex > newIndex)
                    {
                        return true;
                    }

                    // Forbid suppressing "Warning" step if the user is to young
                    /*  if (newIndex === 3)
                    {
                        return true;
                    }  */

                    var form = $(this);

                    // Clean up if user went backward before
                    if (currentIndex < newIndex)
                    {
                        // To remove error styles
                        $(".body:eq(" + newIndex + ") label.error", form).remove();
                        $(".body:eq(" + newIndex + ") .error", form).removeClass("error");  
                    }

                    // Disable validation on fields that are disabled or hidden.
                    form.validate().settings.ignore = ":disabled,:hidden";

                    // Start validation; Prevent going forward if false
                    /* if($("#operationMode").val()==1){
                    	$("#openDate").rules("add", { required:false});
                	} */
                    
                	return true;
					var flag = form.valid();
                    if(!flag){
                    	return flag;
                    }
                    
                    if(currentIndex==0){
                    	//TODO 加一个js验证
                    	/* if($("#operationMode").val()==0 && $.trim($("#openDate").val()) == ""){
                    		 $("#openDate").rules("add", { required:true,messages:{ required:"开放式，此字段必填！"}}); 
                    		return form.valid();
                    	} */
                    	
                    	//addProductBaseInfo(this);
                    }
                    
                    if(currentIndex==1){
                    	if(!$("#contactFile").text()){
                    		$("#productContactFile-error").text("请上传产品合同！");
                    		return false;
                    	}
                    	
                    	$('#modelEditable').dataTable().fnClearTable();
                    }else if(currentIndex==3){
                    	//updateDefaultCommission();
                    }
                    
                    return flag;
                },
                onStepChanged: function (event, currentIndex, priorIndex)
                {
                    // Suppress (skip) "Warning" step if the user is old enough.
                	if(currentIndex==3){
                    	//初始化佣金
                    	oTable.fnClearTable();
                    }else if (currentIndex == 5){
                    	//$(this).steps("previous");
                        //$(this).steps("next");
                        
                        //初始化同类产品
                        initRelatedProduct();
                        //$("a[href=#finish]").css("display","");
                        //$("a[href=#next]").css("display","none");
                    } 

                    // Suppress (skip) "Warning" step if the user is old enough and wants to the previous step.
                   /*   if (currentIndex === 2 && priorIndex === 3)
                    {
                        $(this).steps("previous");
                    }   */
                },
                onFinishing: function (event, currentIndex)
                {
                    var form = $(this);

                    // Disable validation on fields that are disabled.
                    // At this point it's recommended to do an overall check (mean ignoring only disabled fields)
                    form.validate().settings.ignore = ":disabled";

                    if(currentIndex==3){
						 $("#defaultDividend").rules("add", {
							required : true,
							number : true,
							range:[0,100]
						}); 
					 	$("#defaultCommission").rules("add", {
							required : true,
							number : true,
							range:[0,100]
						}); 
					}else{
						$("#defaultDividend").rules("remove"); 
					 	$("#defaultCommission").rules("remove"); 
					}
                    
                    // Start validation; Prevent form submission if false
                    return form.valid();
                },
                onFinished: function (event, currentIndex)
                {
                    var form = $(this);

                    // Submit form input
                   // form.submit();
					
                    if(currentIndex==0){
                    	//TODO 加一个js验证
                    	/* if($("#operationMode").val()==0 && $.trim($("#openDate").val()) == ""){
                    		 $("#openDate").rules("add", { required:true,messages:{ required:"开放式，此字段必填！"}}); 
                    		return form.valid();
                    	} */
                    	
                    	addProductBaseInfo(this);
                    }else if(currentIndex==1){
                    	if(!$("#contactFile").text()){
                    		$("#productContactFile-error").text("请点击上传按钮上传合同！");
                    		return false;
                    	}
                    	
                    	$('#modelEditable').dataTable().fnClearTable();
                    	window.location.href= 'product/list';
                    }else if(currentIndex==3){
                    	updateDefaultCommission();
                    }else{
                    	window.location.href= 'product/list';
                    }
                    
                }
            }).validate({
                        errorPlacement: function (error, element)
                        {
                            element.before(error);
                        },
                        rules: {
                            confirm: {
                                //equalTo: "#password"
                            }
                        }
                    });
			
			ProductGradeModule.init();
			//initSpecifiedContent(); 
			CommissionSetModule.init();
			_initSpecifiedContent();
			getRelatedFile();
			checkOpenDate();
			
			//下拉框
			var config = {
	                '.chosen-select'           : {},
	                '.chosen-select-deselect'  : {allow_single_deselect:true},
	                '.chosen-select-no-single' : {disable_search_threshold:10},
	                '.chosen-select-no-results': {no_results_text:'Oops, nothing found!'},
	                '.chosen-select-width'     : {width:"95%"}
	                }
	        for (var selector in config) {
	                $(selector).chosen(config[selector]);
	        }
			
			     
			
			$("a[href=#previous]").css("display","none");
			//$("a[href=#next]").text("完成");
			$("a[href=#next]").css("display","none");
			$("a[href=#finish]").text("完成");
			//$("a[href=#finish]").css("display","none");
			$("a[href=#cancel]").css("display","none");
			
			$("li[role=tab]").removeClass("disabled");
			$("li[role=tab]").addClass("done");
			//$("li[role=tab]").addClass("current")
			$("li[role=tab]").removeAttr("aria-disabled");
			$("li[role=tab]").first().removeClass("done");
		});

		function initSpecifiedContent() {
			//$("#incomeType").val("${enterprise.incomeType}");
			$("#operationMode").val("${enterprise.operationMode}");
			$("#state").val("${enterprise.state}");
			$("#level").val("${enterprise.level}");
			$("#contactFile").text($("#contactFile").text().match(/[^\\/]*$/)[0]);
			$("#productGroupId").val("${enterprise.productGroupId}");
			$("#riskDisclosureId").val("${enterprise.riskDisclosureId}");
			$("#issuerId").val("${enterprise.issuerId}");
			
			$('#recruitStartTime').datepicker({
				todayBtn : "linked",
				keyboardNavigation : false,
				forceParse : false,
				calendarWeeks : true,
				autoclose : true
			});

			$('#recruitEndTime').datepicker({
				todayBtn : "linked",
				keyboardNavigation : false,
				forceParse : false,
				calendarWeeks : true,
				autoclose : true
			});
			
			$('#recruitStartTime').datepicker()
            .on('changeDate', function(ev){
             	var date = $('#recruitStartTime').val();
             	var date2 = $('#recruitEndTime').val();
             	var startDate = Date.parse(date);
             	var endDate = Date.parse(date2);
             	var today = new Date();
             	var todayTime = today.getTime();
                if(startDate > endDate){
                		bootbox.alert("招募开始时间不能小于截止时间.");
                		$('#recruitStartTime').val("");
                	}
                	$('#recruitStartTime').datepicker('hide');
            }); 
			$('#recruitEndTime').datepicker()
            .on('changeDate', function(ev){
             	var date = $('#recruitStartTime').val();
             	var date2 = $('#recruitEndTime').val();
             	var startDate = Date.parse(date);
             	var endDate = Date.parse(date2);
             	var today = new Date();
             	var todayTime = today.getTime();
                	if(startDate > endDate){
                		bootbox.alert("招募截止时间不能小于开始时间.");
                		$('#recruitEndTime').val("");
                	}
                	$('#recruitEndTime').datepicker('hide');
            }); 
			
			$('#setupTime').datepicker({
				todayBtn : "linked",
				keyboardNavigation : false,
				forceParse : false,
				calendarWeeks : true,
				autoclose : true
			});
			
			$('#interestDate').datepicker({
				todayBtn : "linked",
				keyboardNavigation : false,
				forceParse : false,
				calendarWeeks : true,
				autoclose : true
			});
			
			$.ajax({  
			     url:ctx + '/product/about',// 跳转到 action  
			     //data:json,
			     type:'get',  
			     //async: false,
			     cache:false,  
			     dataType:'json',  
			     success:function(data) {  
			    	 if(data.code == 1){
			    		 var abouts = $("#aboutId").html();
	                		$(data.data).each(function(i,val) { 
	                			abouts += '<option value="'+val.id+'" name="'+val.title + '">'+val.title + '</option>';
	                		});
			    		 $("#aboutId").html(abouts);
			    		 $("#aboutId").val("${enterprise.aboutId}");
			    	 }
			    	 
			      },  
			      error : function() {  
			    	  //bootbox.alert("新增产品基本信息出错。");
			      }  
			 });
			
			if("${enterprise.showApp}"=="true"){
				 $("#showApp").attr("checked", "checked");  
				 $("#pushGroup").show();
			}
			
		}

		function addProductBaseInfo(){
			var json = $('form#addForm').serializeObject();
			json.selectedFundManager = "'"+$("#_fundManager").val()+"'";
			json.selectedInvestorGroup = "'"+$("#_investorGroup").val()+"'";
			json.selectedEmployeeGroup = "'"+$("#_employeeGroup").val()+"'";
         	
			$.ajax({  
			     url:ctx + '/product/doAdd',// 跳转到 action  
			     data:json,
			     type:'post',  
			     //async: false,
			     cache:false,  
			     dataType:'json',  
			     success:function(data) {  
			    	 if(data.code == 1){
			    		 $("input[name=id]").val(data.data.id);
			    		 $("#productId").val(data.data.id);
			    		 uploadProductImage();
			    		 //_initSpecifiedContent(data.data.defaultCommissionSet);
			    		 bootbox.dialog({
	        					message : "修改成功！ ",
	        					title : "温馨提示：",
	        					buttons : {
	        						main : {
	        							label : "确定",
	        							className : "btn btn-outline btn-primary",
	        							callback : function() {
	        								window.location.href= 'product/list';
	        							}
	        						}
	        					}
	        				});
			    		 return true;
			    	 }
			    	 
			    	 return false;
			      },  
			      error : function() {  
			    	  //bootbox.alert("新增产品基本信息出错。");
			    	  return false;
			      }  
			 });
		}
			
		function uploadProductImage(){
			if(!$("#productImage").val()){
				return;
			}
			
			 $.ajaxFileUpload({
	                url: ctx + '/product/upload',
	                type: 'post',
	                secureuri: false,
	                fileElementId: 'productImage',
	                dataType: 'json',
	                data: {'id':$("input[name=id]").val()},
	                success: function(data, status){
	                	if (data.code == 1) {
	                        $("#showProductImage").attr("src","${imagePrefix}"+data.data.thumbnail);
	                        $("#productImageDiv").css("display","");
	                        $("#productImage").rules("remove");
	                	} else {
	                		bootbox.alert(data.message);
	                	}
	                },
	                error: function(msg, status, e){
	                	bootbox.alert("上传产品图片出错。");
	                }
	            });
			 } 
		
		function uploadProductContact(){
			if(!$("#productContactFile").val()){
				return;
			}
			
			 $.ajaxFileUpload({
	                url: ctx + '/product/upload',
	                type: 'post',
	                secureuri: false,
	                fileElementId: 'productContactFile',
	                dataType: 'json',
	                data: {'id': $("input[name=id]").val()},
	                success: function(data, status){
	                	if (data.code == 1) {
	                        $("#contactFile").text(data.data.contactFile.match(/[^\\/]*$/)[0]);
	                        $("#reviewContact").attr("onclick","javascript:location.href='product/downloadEffect?productId="+data.data.id+"'");
	                        $("#productContactFileDiv").css("display","");
	                        $("#productContactFile").rules("remove");
	                        $("#productContactFile-error").text("");
	                        bootbox.alert("上传成功！");
	                	} else {
	                		bootbox.alert("上传失败！");
	                	}
	                },
	                error: function(msg, status, e){
	                	bootbox.alert("上传失败！");
	                }
	            });
			 } 
		
		function _showApp(obj){
    		$("#showApp").val(obj.checked);
    		if(obj.checked){
    			$("#pushGroup").show();
    		}else{
    			$("#pushGroup").hide();
    		}
    	}
	</script>
	
   
   
    <!-- 佣金设置 -->
    <script>
       
        function _initSpecifiedContent(){
        	if("${enterprise.defaultCommissionSet}"=="true"){
        		$("input[type='radio'][value='option1']").attr("checked","checked" );
        		$("#customSet").hide();
        		$("#default_comm_div").show();
        	}else{
        		$("input[type='radio'][value='option2']").attr("checked","checked" );
        		$("#customSet").show();
        		$("#default_comm_div").hide();
        	}
        	
        	 $("input[name='optionsRadios']").bind("click",function(){ 
                 
        	        //测试操作代码 
        	        if($(this).val()=="option1"){
        	        	$("#customSet").hide();
        	        	$("#default_comm_div").show();
        	        	updateCommissionSetButton(true);
        	        }else{
        	        	var flag = $("#addForm").valid();
        	        	if(!flag){
        	        		return false;
        	        	}
        	        	
        	        	// 1-表示新增或刷新默认佣金值，再刷新自定义佣金表
        	        	updateDefaultCommission(1);
        	        	$("#customSet").show();
        	        	$("#default_comm_div").hide();
        	        	updateCommissionSetButton(false);
        	        }
        	 });
        }
        
        function updateCommissionSetButton(flag){
        	$.ajax({
            	type:"get",
                url: ctx + "/product/update",
                data:"id="+$("#productId").val()+"&defaultCommissionSet="+flag,
                dataType:"json",
                success: function(data){
                	
                },
                error: function (msg) {
                	bootbox.alert(msg.message);
                }
            });
        }
        
        var employeeId;
        function setRate(){
        	var old_val = $("#old_val").val();
        	var new_val = $("#new_val").val();
        	if(null == new_val || "" == new_val.trim() || old_val==new_val){
        		bootbox.alert("请输入与原费率不同的且不为空的值！");
        		return;
        	}
        	
        	if(new_val<0||new_val>100){
        		bootbox.alert("请输入0-100费率值！");
        		return;
        	}
        	
            var productId = $("#productId").val();
            var param = $("#d_title").text().indexOf("提成")!=-1?"&dividendRate="+new_val:"&commissionRate="+new_val;
            
        	$.ajax({
            	type:"post",
                url: ctx + "/product/setRate",
                data:"productId=" + productId +"&employeeId="+employeeId+param,
                dataType:"json",
                success: function(data){
                	if (data.code == 1) {
                		modal.modal('hide');
                		bootbox.alert("设置成功！");
                		oTable.fnClearTable();
                	}
                },
                error: function (msg) {
                	bootbox.alert(msg.message);
                }
            });
        }
        
        function updateDefaultCommission(flag){
        	$.ajax({
            	type:"get",
                url: ctx + "/product/update",
                data:"id="+$("#productId").val()+"&defaultDividend="+$("input[name=defaultDividend]").val()+"&defaultCommission="+$("input[name=defaultCommission]").val(),
                dataType:"json",
                success: function(data){
                	if(flag==1){
                		oTable.fnClearTable();
                	}else{
                		bootbox.dialog({
        					message : "修改成功！ ",
        					title : "温馨提示：",
        					buttons : {
        						main : {
        							label : "确定",
        							className : "btn btn-outline btn-primary",
        							callback : function() {
        								window.location.href= 'product/list';
        							}
        						}
        					}
        				});
                	}
                },
                error: function (msg) {
                	bootbox.alert(msg.message);
                }
            });
        }
    </script>
    
    <!-- 产品相关文件 -->
    <script>
        
        function uploadRelatedFile(){
			if(!$("#relatedFile").val()){
				bootbox.alert("请先添加文件！");
				return;
			}
			
			 $.ajaxFileUpload({
	                url: ctx + '/productAttachment/uploadRelatedFile',
	                type: 'post',
	                secureuri: false,
	                fileElementId: 'relatedFile',
	                dataType: 'json',
	                data: {'productId': $("input[name=id]").val()},
	                success: function(data, status){
	                	if (data.code == 1) {
	                		bootbox.dialog({
	        					message : "上传成功！ ",
	        					title : "温馨提示：",
	        					buttons : {
	        						main : {
	        							label : "确定",
	        							className : "btn btn-outline btn-primary",
	        							callback : function() {
	        								getRelatedFile();
	        							}
	        						}
	        					}
	        				});
	                		
	                	} else {
	                		bootbox.alert(data.message);
	                	}
	                },
	                error: function(msg, status, e){
	                	bootbox.alert("上传失败！");
	                }
	            });
			 } 
        
        
        function deleteFile(obj){
            bootbox.confirm("您确定要删除这个文件?", function(result) {
                if (result) {
                	var nRow = $(obj).parents('div')[0];
                    var id = nRow.id;
                    
                    $.ajax({
                    	type:"get",
                        url: ctx + "/productAttachment/delete",
                        data:"id=" + id,
                        dataType:"json",
                        success: function(msg){
                        	if (msg.code == 1) {
                        		getRelatedFile();
                        		bootbox.alert("删除文件成功！");
                        	} else {
                        		bootbox.alert("删除文件失败！");
                        	}
                        },
                        error: function (msg) {
                        	bootbox.alert(msg.message);
                        }
                    });
                }
            });
        }
        
        function getRelatedFile(){
        	$.ajax({
            	type:"get",
                url: ctx + "/productAttachment/query/"+$("input[name=id]").val(),
                dataType:"json",
                success: function(data){
                	if (data.code == 1) {
                		var objs = data.data.relatedFile;
                    	var html = "";
                    	var closeBttn = '<button onclick="deleteFile(this)" style="border:0px;background:#0f0;background-color:transparent;" title="Close">'+
    						            '<span aria-hidden="true">&times;</span>'+
    							        '<span class="hide">Close</span>'+
    					                '</button>';
    					
                    	for(var i=0;i<objs.length;i++){
                    		var id = objs[i].id;
                    		var fileName = objs[i].fileName;
                    		var renameBttn = '<button id="'+id+'" name="'+fileName+'" type="button" class="btn btn-outline btn-primary btn-xs" onclick="showRenameDialog(this)">重命名</button>';
                    		html+="<div style='padding-top:2px' id='"+id+"'>"+fileName+closeBttn+renameBttn+"</div>";
                    	}
                    	$("#relatedFileId").html(html);
                	}
                },
                error: function (msg) {
                	bootbox.alert(msg.message);
                }
            });
        }
        var modal;
        function showRenameDialog(obj){
        	var filename = $(obj).attr('name').split(".")[0];
        	$("#o_renameFileName").val(filename);
        	$("#renameFileName").val(filename);
        	$("#renameFileName").attr('name',$(obj).attr('id'));
        	modal = $('#updateModel_relatedFile').modal('show');
        }
        
        function renameFile(){
        	var o_filename = $("#o_renameFileName").val();
        	var filename = $("#renameFileName").val();
        	if(o_filename==filename){
        		bootbox.alert("请输入与原文件名不同的名字！");
        		return;
        	}
        	
            var id = $("#renameFileName").attr('name');

        	$.ajax({
            	type:"post",
                url: ctx + "/productAttachment/rename",
                data:"id=" + id+"&fileName="+filename,
                dataType:"json",
                success: function(data){
                	if (data.code == 1) {
                		modal.modal('hide');
                		bootbox.alert("更新文件名字成功！");
                		getRelatedFile();
                	}
                },
                error: function (msg) {
                	bootbox.alert(msg.message);
                }
            });
        }
    </script>
    
     <!-- 同类产品 -->
    <script>
	    function initRelatedProduct(){
	    	$.ajax({
            	type:"get",
                url: ctx + "/productRelated/list/"+$("input[name=id]").val(),
                dataType:"json",
                success: function(data){
                	if (data.code == 1) {
                		var relatedUNSelected = "";
                		$(data.data.productList).each(function(i,val) { 
                			relatedUNSelected += '<option value="'+val.id+'" name="'+val.briefName + '">'+val.briefName + '</option>';
                		});
                		$("#relatedUNSelected").html(relatedUNSelected);
                		
                		var relatedSelected = "";
                		$(data.data.relatedProductList).each(function(i,val) { 
                			relatedSelected += '<option value="'+val.id+'" name="'+val.briefName + '">'+val.briefName + '</option>';
                		});
                		$("#relatedSelected").html(relatedSelected);
                	}
                },
                error: function (msg) {
                	bootbox.alert(msg.message);
                }
            });
	    }
        
        function _remove() {
    		var se1 = $('#relatedSelected')[0];
    		var se2 = $('#relatedUNSelected')[0];
    		var lenth = se1.length;
    		var i=0;
    	    for(;i<lenth; ) {
    	        if(se1[i].selected) {
    	            var opt = document.createElement('option');
    	            opt.value = se1[i].value;
    	            var node = document.createTextNode(se1[i].innerHTML);
    	            opt.appendChild(node);
    	            se2.appendChild(opt);
    	            se1.removeChild(se1[i]);
    	            lenth = lenth -1;
    	            i=0
    	        }
    	        else{
    	        	i++;
    	        }
    	    }
    	}
    	function add() {
    		var se1 = $('#relatedSelected')[0];
    		var se2 = $('#relatedUNSelected')[0];
    		var lenth = se2.length;
    		var i=0;
    	    for(;i<lenth;) {
    	        if(se2[i].selected) {
    	            var opt = document.createElement('option');
    	            opt.value = se2[i].value;
    	            var node = document.createTextNode(se2[i].innerHTML);
    	            opt.appendChild(node);
    	            se1.appendChild(opt);
    	            se2.removeChild(se2[i]);
    	            lenth = lenth -1;
    	            i=0
    	        }else{
    	        	i++;
    	        }
    	    }
    	}
    	
    	function saveRelatedProduct(){
    		var se1 = $('#relatedSelected')[0];
    		var arr = new Array();
    	    for(var i=0;i<se1.length;i++) {
    	    	arr.push(se1[i].value);
    	    }
    	    
    	    var se2 = $('#relatedUNSelected')[0];
    	    if(se1.length==0&&se2.length==0){
    	    	return;
    	    }
    	    
    	    $.ajax({
            	type:"post",
                url: ctx + "/productRelated/save",
                data:"productId="+$("input[name=id]").val()+"&relatedIds=" +arr ,
                dataType:"json",
                success: function(msg){
                	if (msg.code == 1) {
                		bootbox.dialog({
        					message : "保存相关产品成功！",
        					//title : "温馨提示：",
        					buttons : {
        						main : {
        							label : "确定",
        							className : "btn btn-outline btn-primary",
        							callback : function() {
        								initRelatedProduct();
        							}
        						}
        					}
        				});
                	} else {
                		bootbox.alert("保存相关产品失败！");
                	}
                },
                error: function (msg) {
                	bootbox.alert(msg.message);
                }
            });
    	}
    </script>
    
    <!-- 新增产品组别 -->
    <script>
    	var productGroupModal;
    	var currentId = "";
	    function showProductGroupDialog(){
        	$("#newProductGroupName").val("");
        	productGroupModal = $('#newProductGroup').modal('show');
        	currentId = $("#productGroupId").val();
	    }
	    
    	function newProductGroup(){
    		var name = $("#newProductGroupName").val().trim();
    		if(name == ""){
        		bootbox.alert("产品组别不能为空！");
        		return;
        	}
    		
    		$.ajax({
             	type:"post",
                 url: ctx + "/productGroup/newGroup",
                 data: "name=" + name,
                 dataType:"json",
                 success: function(data){
                	 if(data.code==1){
                		productGroupModal.modal('hide');
                     	bootbox.alert("新增产品组别成功！");
                     	
                     	var groupOption = '<option value="">无</option>';
                     	$.each(data.data, function(n, value) {   
                              groupOption += '<option value="'+value.id+'" name="'+value.name+'">'+value.name+'</option>';    
                        });  
                   
                       $("#productGroupId").html(groupOption);  
                       $("#productGroupId").val(currentId);
                 	}else{
	                    bootbox.alert(data.message);
                 	}
                 },
                 error: function (msg) {
                 	bootbox.alert(msg.message);
                 }
          	});
    	}
    </script>
    
</body>
</html>